﻿using DataAchive.Common;
using DataAchive.Extend;
using DataAchive.Helper;
using DataAchive.Model.DataShow;
using DataAchive.Model.Excel.Export;
using NPOI.OpenXmlFormats.Dml.ChartDrawing;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.UI;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace DataAchive
{
    /// <summary>
    /// DataShowMachinedWindow.xaml 的交互逻辑
    /// </summary>
    public partial class DataShowMachinedWindow : Window
    {
        private List<GroupBox> groupBoxes;
        private static List<KeyValuePair<string, string>> _pairs = null;
        System.Timers.Timer _timer = new System.Timers.Timer()
        {
            AutoReset = true,
            Enabled = true,
            Interval = 1000 * 60 * 3
        };
        ObservableCollection<string> ErrorConnectViewModels = new ObservableCollection<string>();        

        public DataShowMachinedWindow()
        {
            InitializeComponent();
            DataShowConnectorHelper.GetXmlSetting();           
            _pairs = DataShowConnectorHelper.dataShowSiteAndConnections;

           
            
            errorListBox.DataContext = ErrorConnectViewModels;
         
            updateDate.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            groupBoxes = bigUniform.Children.OfType<GroupBox>().ToList();
            foreach (GroupBox groupBox in groupBoxes)
            {
               var dataShowViewModel = new DataShowViewModel()
                {
                    EveryOneDefectRates = new ObservableCollection<EveryOneDefectRate>()
                };
                groupBox.DataContext = dataShowViewModel;
            }
            Task.Run(() =>
            {                   
                GetDefectData();
            });

            _timer.Elapsed += _timer_Elapsed;
        }

        private void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            GetDefectData();
            Dispatcher.BeginInvoke(new Action(() =>
            {
                updateDate.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                ErrorConnectViewModels.Clear();
            }));

        }

        //循环ip,拉取数据，间隔3分钟，刷新

        void GetDefectData()
        {
            SoftCommon.Log.Write($"ip项目数量为{_pairs.Count},获取数据...");
            WhereQ whereQ = new WhereQ()
            {
                BeginTime =DateTime.Now.Hour==0&&DateTime.Now.Minute<=3? DateTime.Now.AddMinutes(-6): DateTime.Now.Date,
                EndTime = DateTime.Now.AddMinutes(-3),
            };
           

            int count = 0;
            foreach (var itemPair in _pairs)
            {
                try
                {
                    DataShowViewModel dataShowViewModel = null;
                    count++;
                    if (count > 4)
                    {
                        SoftCommon.Log.Write("itemPair 数量大于4,跳过");
                        break;
                    }

                    Dispatcher.Invoke(new Action(() =>
                    {
            
                        if (groupBoxes[count - 1].DataContext != null)
                        {
                            dataShowViewModel = groupBoxes[count - 1].DataContext as DataShowViewModel;
                        }
                        else
                        {
                            groupBoxes[count - 1].DataContext = dataShowViewModel;
                        }

                    }));
                    //获取数据
                    dataShowViewModel.MachineInfo = itemPair.Key;
                    if (DataShowConnectorHelper.connectionMachines.Count < count)
                    {
                        SoftCommon.Log.Write("机器号数量异常:"+ DataShowConnectorHelper.connectionMachines.Count);
                    }
                    else
                    {
                        var kvs = DataShowConnectorHelper.connectionMachines[count - 1];
                        if (string.IsNullOrWhiteSpace(kvs.Value))
                        {
                            SoftCommon.Log.Write($"链接{kvs.Key}机器号为空.");
                        }
                        else
                        {
                            SoftCommon.Log.Write($"链接{kvs.Key}机器号{kvs.Value}");
                        }
                       var machines = new List<string>( kvs.Value.Split(','));
                       whereQ.ManyEquitepmentIds=machines;
                    }
                   

                    List<ColRowReport> lsresult = WindowShow.GetColRowReportsCommon(whereQ, itemPair.Value);
                    SoftCommon.Log.Write($"{itemPair.Key}获取到数据条数{lsresult.Count}。");
                    var totalNum = lsresult.Count();
                    var zhitong = lsresult.Count(x => x.HumanJudgeTime != null && x.HumanJudgeTime == TimeSpan.Zero);
                    var wupan = lsresult.Count(x => !string.IsNullOrWhiteSpace(x.LouJianOrGuopan) && x.LouJianOrGuopan.Equals("过判"));
                    var ng = lsresult.Count(x => !string.IsNullOrWhiteSpace(x.LouJianOrGuopan) && x.LouJianOrGuopan.Equals("NG"));

                    //DataShowViewModel dataShowViewModel = new DataShowViewModel()
                    //{
                    //    DirectRate = totalNum == 0 ? 0 : Math.Round((decimal)zhitong / totalNum, 4),
                    //    OverJudge = wupan
                    //};
                    dataShowViewModel.DirectRate = totalNum == 0 ? 0 : Math.Round((decimal)zhitong / totalNum, 4);
                    dataShowViewModel.OverJudge = wupan;
                    dataShowViewModel.ProductNumber = totalNum;

                    var reportDefectData = AiDefectStaticRRR.GetHReportDataAi11111(lsresult);
                    var totalDefectNumber = reportDefectData.Sum(x => x.DefectCount);

                    List<EveryOneDefectRate> defectRateStaticColumns = new List<EveryOneDefectRate>();
                    foreach (var item in reportDefectData)
                    {
                        EveryOneDefectRate defectRateStatic = new EveryOneDefectRate()
                        {
                            DefectNumber = item.DefectCount,
                            DefectName = item.DefectName,
                            DefectRate = totalDefectNumber == 0 ? 0 : Math.Round((decimal)item.DefectCount / totalDefectNumber, 4)
                        };
                        defectRateStaticColumns.Add(defectRateStatic);

                    }
                    if (defectRateStaticColumns.Count > 7)
                    {
                        defectRateStaticColumns = defectRateStaticColumns.OrderByDescending(x=>x.DefectNumber).Take(7).ToList();
                    }
                    // dataShowViewModel.EveryOneDefectRates = defectRateStaticColumns;                  
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        dataShowViewModel.EveryOneDefectRates.Clear();
                        foreach (var item in defectRateStaticColumns)
                        {
                            dataShowViewModel.EveryOneDefectRates.Add(item);
                        }
                    }));
                }
                catch (Exception ex)
                {

                    SoftCommon.Log.Write("GetDefectData->whereQ：" + ex.Message);
               
                   
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                         ErrorConnectViewModels.Add(itemPair.Key);
                    }));
                }



            }



        }
    }
}
